package com.jiuzhou.surery.Controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jiuzhou.surery.beans.Item;
import com.jiuzhou.surery.db.ItemRepository;

@Controller
@RequestMapping("/items")
public class ItemsController {
    

    private final ItemRepository itemRepository;


    public ItemsController(ItemRepository itemRepository) {
        this.itemRepository = itemRepository;
    }


    @GetMapping("/list")
    public String list(Model model) {
        model.addAttribute("items", itemRepository.findAll());
        return "items/list";
    }

    @GetMapping("/add")
    public String add(Model model){
        model.addAttribute("item", new Item());
        return "/items/add";
    }


    @PostMapping("/add")
    public String add(@ModelAttribute Item item, Model model){
        itemRepository.save(item);
        // 添加当前时间到模型
        addCurrentTimeToModel(model);
        return "redirect:/items/list";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") long id) {
        itemRepository.deleteById(id);
        return "redirect:/items/list";
    }

     private void addCurrentTimeToModel(Model model) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTime = now.format(formatter);
        model.addAttribute("currentTime", formattedTime);
    }
}
